<template>
    <div class="video-analysis">
        <div class="row">
            <div class="col-md-8">
                <video-player class="video-player vjs-custom-skin" ref="videoPlayer" :playsinline="true"
                    :options="playerOptions">
                </video-player>
            </div>
            <div class="col-md-4">
                <div class="stats-panel">
                    <!-- <h4>目标检测</h4> -->
                    <div ref="barChartContainer" style="width: 100%; height: 500px;"></div>

                    <h2>行为分布</h2>
                    <div id="pie-chart-behavior" class="chart"></div>

                    <h4 class="mt-4">异常事件</h4>
                    <ul class="abnormal-events">
                        <li v-for="(event, index) in abnormalEvents" :key="index">
                            <span class="time-info">
                                {{ formatTime(event.start_time) }}
                                <span class="duration">(持续 {{ event.duration.toFixed(1) }} 秒)</span>
                            </span>
                            <span class="event-type">{{ event.type }}</span>
                            <span class="objects">涉及对象：{{ event.unique_objects.join(', ') }}</span>
                            <button @click="jumpToTime(event.start_time)" class="btn-locate">
                                <i class="fas fa-map-marker-alt"></i> 定位
                            </button>
                        </li>
                    </ul>
                </div>
            </div>
        </div>

        <!-- <div class="chart-container">
            <div id="timeline-chart" class="chart"></div>
        </div> -->

        <div class="row mt-4">
            <div class="col-12">
                <!-- <h2>行为时间线</h2> -->
                <div id="timeline-chart" class="chart"></div>
            </div>
        </div>

        <!-- 视频信息图表展示 -->
        <div class="video-analysis">
            <analysis-charts :frames-data="analysisData.frames" />
        </div>
    </div>
</template>

<script>
import axios from 'axios'
import * as echarts from 'echarts'
import AnalysisCharts from './AnalysisCharts.vue'

export default {
    components: {
        AnalysisCharts
    },
    props: ['taskId'],
    data() {
        return {
            processedUrl: '',
            playerOptions: {
                autoplay: false,
                controls: true,
                sources: [{
                    type: "video/mp4",
                    src: this.processedUrl
                }],
                fluid: true
            },
            objectCounter: {},
            behaviorStats: {},
            abnormalEvents: [],
            timelineData: [],
            pieChart: null,
            timelineChart: null,
            analysisData: {}  // 从API获取的数据
        }
    },
    methods: {
        async fetchAnalysisData() {
            try {
                const res = await axios.get(`/analysis/${this.taskId}`)
                console.log(res.data)//behavior_distribution
                this.objectCounter = { ...res.data.data.object_counter }
                this.behaviorStats = { ...res.data.data.behavior_stats }
                this.abnormalEvents = res.data.data.abnormal_events.map(e => ({
                    ...e,
                    start_time: e.start_frame / res.data.data.fps,
                    end_time: e.end_frame / res.data.data.fps,
                    duration: e.duration,
                    unique_objects: [...new Set(e.objects)] // 去重处理
                }))
                this.timelineData = [...res.data.data.timeline]
                this.analysisData = res.data.data
                this.$nextTick(() => {
                    this.initCharts()
                })
            } catch (error) {
                console.error('获取分析数据失败:', error)
            }
        },
        initBarChart() {
            // 初始化柱状图
            this.barChart = echarts.init(this.$refs.barChartContainer)
            // 将数据转换为排序后的数组（按值降序）
            const sortedData = Object.entries(this.objectCounter)
                .sort(([, a], [, b]) => b - a)
                .map(([name, value]) => ({ name, value }))

            this.barChart.setOption({
                title: {
                    text: '目标检测统计',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    },
                    formatter: '{b}: {c}'
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '15%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: sortedData.map(item => item.name),
                    axisLabel: {
                        rotate: 45,
                        fontSize: 12,
                        margin: 15
                    }
                },
                yAxis: {
                    type: 'value',
                    name: 'Count',
                    nameLocation: 'end',
                    axisLine: {
                        show: true
                    }
                },
                series: [{
                    type: 'bar',
                    data: sortedData,
                    itemStyle: {
                        color: (params) => {
                            // 为不同范围的值设置不同颜色
                            const value = sortedData[params.dataIndex].value
                            return value > 1000 ? '#c23531' :
                                value > 100 ? '#2f4554' :
                                    value > 10 ? '#61a0a8' :
                                        '#d48265'
                        }
                    },
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{c}'
                    },
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }],
                dataZoom: [{
                    type: 'slider',
                    show: true,
                    yAxisIndex: 0,
                    filterMode: 'empty',
                    start: 0,
                    end: 100
                }]
            })
        },
        initPieChart() {
            // 初始化饼图
            // 显示各类行为（行走、奔跑、打架等）的占比
            this.pieChart = echarts.init(document.getElementById('pie-chart-behavior'))
            this.pieChart.setOption({
                // title: {
                //     text: '行为分布',
                //     left: 'center'
                // },
                tooltip: { trigger: 'item' },
                series: [{
                    type: 'pie',
                    data: Object.entries(this.behaviorStats).map(([name, value]) => ({
                        name, value
                    }))
                }]
            })
        },
        // initTimelineChart() {
        //     // 初始化时间线图
        //     // 显示异常行为发生的时间点
        //     this.timelineChart = echarts.init(document.getElementById('timeline-chart'))
        //     this.timelineChart.setOption({
        //         title: {
        //             text: '行为时间线分析',
        //             left: 'center',
        //             textStyle: { color: '#666' }
        //         },
        //         tooltip: {
        //             trigger: 'axis',
        //             formatter: params => {
        //                 const data = params[0].data
        //                 return `
        //                     <strong>${data.time}</strong><br/>
        //                     行为数量: ${data.value}<br/>
        //                     主要行为: ${data.mainBehavior}<br/>
        //                     异常状态: ${data.abnormal ? '⚠️ 存在异常' : '正常'}
        //     `
        //             }
        //         },
        //         xAxis: {
        //             type: 'category',
        //             data: this.timelineData.map(d => d.time.toFixed(1))
        //         },
        //         yAxis: { type: 'value' },
        //         series: [{//d => d.behaviors.length
        //             data: this.timelineData.map(d => d.abnormal == true),//d => d.abnormal == true
        //             type: 'line',
        //             smooth: true
        //         }]
        //     })
        // },
        initTimelineChart() {
            // 处理时间线数据
            const chartData = this.timelineData.map(d => ({
                // 转换为分钟:秒格式
                time: `${Math.floor(d.time / 60)}:${(d.time % 60).toFixed(0).padStart(2, '0')}`,
                value: d.behaviors.length,
                abnormal: d.abnormal,
                // 提取主要行为（出现次数最多的）
                mainBehavior: this.getDominantBehavior(d.behaviors)
            }))
            this.timelineChart = echarts.init(document.getElementById('timeline-chart'))
            // 配置图表选项
            this.timelineChart.setOption({
                title: {
                    text: '行为时间线分析',
                    left: 'center',
                    textStyle: { color: '#666' }
                },
                tooltip: {
                    trigger: 'axis',
                    formatter: params => {
                        const data = params[0].data
                        return `
                                <strong>${data.time}</strong><br/>
                                行为数量: ${data.value}<br/>
                                主要行为: ${data.mainBehavior}<br/>
                                异常状态: ${data.abnormal ? '⚠️ 存在异常' : '正常'}
                                `
                    }
                },
                xAxis: {
                    type: 'category',
                    data: chartData.map(d => d.time),
                    axisLabel: { rotate: 45 }
                },
                yAxis: {
                    type: 'value',
                    name: '行为数量'
                },
                visualMap: {
                    top: 30,
                    right: 10,
                    pieces: [{ gt: 0, lte: 0, color: '#91cc75' }, // 正常
                    { gt: 0, color: '#ee6666' }], // 异常
                    dimension: 'abnormal',
                    show: false
                },
                series: [{
                    data: chartData,
                    type: 'line',
                    smooth: true,
                    symbol: 'circle',
                    symbolSize: d => d.abnormal ? 8 : 6, // 异常点放大
                    itemStyle: {
                        color: params => params.data.abnormal ? '#ee6666' : '#91cc75'
                    },
                    lineStyle: {
                        color: '#5470c6',
                        width: 2
                    },
                    areaStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: 'rgba(84,112,198,0.6)' },
                            { offset: 1, color: 'rgba(84,112,198,0.02)' }
                        ])
                    },
                    markPoint: {
                        data: chartData
                            .filter(d => d.abnormal)
                            .map(d => ({
                                name: '异常点',
                                coord: [d.time, d.value],
                                symbolSize: 20,
                                itemStyle: { color: '#ee6666' }
                            }))
                    }
                }]
            })
        },
        getDominantBehavior(behaviors) {
            // 防御性编程：处理无效输入
            if (!Array.isArray(behaviors)) {
                console.warn('Invalid behaviors input:', behaviors)
                return 'unknown'
            }

            // 处理空数组情况
            if (behaviors.length === 0) {
                return 'no-behavior'
            }

            // 统计频率
            const countMap = behaviors.reduce((acc, cur) => {
                const key = String(cur).trim() || 'unknown' // 规范化行为名称
                acc[key] = (acc[key] || 0) + 1
                return acc
            }, {})

            // 获取排序后的条目
            const sortedEntries = Object.entries(countMap).sort((a, b) => {
                // 先按频率降序，再按字母升序
                return b[1] - a[1] || a[0].localeCompare(b[0])
            })

            // 处理所有行为出现次数相同的情况
            if (sortedEntries.length === 0) {
                return 'unknown'
            }

            // 返回第一个条目（最高频），若出现平票则按字母顺序选第一个
            return sortedEntries[0][0] || 'unknown'
        },
        initCharts() {
            // 销毁旧图表实例
            if (this.barChart) this.barChart.dispose()
            if (this.pieChart) this.pieChart.dispose()
            if (this.timelineChart) this.timelineChart.dispose()

            this.initBarChart()
            this.initPieChart()
            this.initTimelineChart()
        },
        jumpToTime(timeInSeconds) {
            try {
                const player = this.$refs.videoPlayer.player
                const duration = player.duration()

                // 有效性校验
                if (typeof timeInSeconds !== 'number' || timeInSeconds < 0) {
                    console.error('无效的时间参数:', timeInSeconds)
                    return
                }

                // 边界检查
                const safeTime = Math.min(Math.max(timeInSeconds, 0), duration - 0.1)

                // 精确跳转（使用官方API）
                player.currentTime(safeTime)

                // 强制刷新播放器状态
                if (player.paused()) {
                    player.play().then(() => {
                        player.pause()
                    }).catch(error => {
                        console.log('自动播放阻止:', error)
                    })
                }
                this.$notify.info({
                    title: '消息',
                    message: `成功跳转到 ${safeTime.toFixed(2)} 秒`
                });
                console.log(`成功跳转到 ${safeTime.toFixed(2)} 秒`)
            } catch (error) {
                console.error('跳转失败:', error)
                this.$message.error(`视频定位失败: ${error.message}`)
            }
        },
        formatTime(seconds) {
            const mins = Math.floor(seconds / 60)
            const secs = Math.floor(seconds % 60)
            return `${mins}:${secs.toString().padStart(2, '0')}`
        }
    },
    mounted() {
        this.processedUrl = `http://localhost:5000/processed_video/${this.taskId}`
        this.playerOptions.sources[0].src = this.processedUrl
        this.fetchAnalysisData()
    },
    beforeDestroy() {
        if (this.barChart) this.barChart.dispose()
        if (this.pieChart) this.pieChart.dispose()
        if (this.timelineChart) this.timelineChart.dispose()
    }
}
</script>

<style scoped>
.chart-container {
    background: #fff;
    border-radius: 8px;
    padding: 15px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stats-panel {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 8px;
}

.abnormal-events {
    list-style: none;
    padding: 0;
}

.abnormal-events li {
    padding: 8px 0;
    border-bottom: 1px solid #eee;
}

.chart {
    width: 100%;
    height: 300px;
}

.abnormal-events {
    list-style: none;
    padding: 0;
    max-height: 300px;
    overflow-y: auto;
}

.abnormal-events li {
    padding: 12px;
    margin: 8px 0;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.time-info {
    width: 160px;
    color: #666;
}

.duration {
    display: block;
    font-size: 0.9em;
    color: #999;
}

.event-type {
    flex: 1;
    margin: 0 20px;
    font-weight: bold;
    color: #e74c3c;
}

.objects {
    width: 120px;
    font-size: 0.9em;
    color: #3498db;
}

.btn-locate {
    padding: 6px 12px;
    background: #3498db;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: background 0.3s;
}

.btn-locate:hover {
    background: #2980b9;
}

.btn-locate i {
    margin-right: 5px;
}
</style>